package cn.com.shopec.erp.base.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.com.shopec.erp.base.commo.SupplierExcel;
import cn.com.shopec.erp.base.entity.SupplierAccounts;
import cn.com.shopec.erp.base.entity.SupplierInfo;
import cn.com.shopec.erp.base.service.ISupplierAccountsService;
import cn.com.shopec.erp.base.service.ISupplierInfoService;
import cn.com.shopec.erp.base.vo.SupplierVo;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.excep.WMSException;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.JsonHelper;
import cn.com.shopec.erp.common.utils.JsonHelper2;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.MD5Util;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.product.entity.ProdSupplier;
import cn.com.shopec.erp.product.service.IBrandService;
import cn.com.shopec.erp.product.service.IProdSupplierService;
import cn.com.shopec.erp.product.vo.BrandVo;
import cn.com.shopec.erp.product.vo.ProdSupplierVo;
import cn.com.shopec.erp.system.common.UserUtils;
import cn.com.shopec.erp.system.service.IUserService;
import cn.com.shopec.erp.system.vo.RoleVo;

/**
 * 供应商基本信息
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("base/supplierInfo")
public class SupplierInfoController {

	/** 日志. */
	private Logger log = Logger.getLogger(SupplierInfoController.class);
	
	@Resource
	private ISupplierInfoService supplierInfoService;

	@Resource
	private ISupplierAccountsService supplierAccountsService;

	@Resource
	private IProdSupplierService prodSupplierService;

	@Resource
	private IBrandService brandService;

	@Resource
	private IUserService userService;

	/**
	 * 跳转到新增供应商页面
	 * 
	 * @return
	 */
	@RequestMapping("toAddSupplier")
	public String toAddSupplier() {
		SupplierAccounts[] sa = null;
		ModelMap map = new ModelMap();
		map.put("sa", sa);
		return "/base/add_supplier";

	}

	/**
	 * 新增供应商基本信息
	 * 
	 * @param supplierInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("c_supplierInfo")
	@ResponseBody
	public String c_supplierInfo(SupplierVo vo) throws Exception {

		if (null != vo) {
			try {
				this.supplierInfoService.addSupplierInfo(vo);
				return SZSCMConstant.SUCCESS;
			} catch (WMSException e) {
				log.info("WMS");
				return SZSCMConstant.WMS_FAIL;

			} catch (Exception e) {
				log.info("c_supplierInfo" + e.getMessage(), e);
			}
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 跳转到修改供应商页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toUpdateSupplier")
	public String toUpdateSupplier(String code, ModelMap map) throws Exception {
		SupplierInfo info = supplierInfoService.getSupplierInfoCode(code);
		List<SupplierAccounts> purList = supplierAccountsService.getSupplierAccountsListByCode(info.getCode(), 1); // 1:购销
		List<SupplierAccounts> conList = supplierAccountsService.getSupplierAccountsListByCode(info.getCode(), 2); // 2:代销
		if (null != purList && purList.size() > 0) {
			for (SupplierAccounts sa : purList) {
				sa.setSupplierInfo(null);
			}
		}
		if (null != conList && conList.size() > 0) {
			for (SupplierAccounts sa : conList) {
				sa.setSupplierInfo(null);
			}
		}
		String purJsonStr = JsonHelper.toJson(purList);
		String conJsonStr = JsonHelper.toJson(conList);
		map.put("SupplierInfo", info);
		map.put("purJsonStr", purJsonStr);
		map.put("conJsonStr", conJsonStr);
		return "/base/update_supplier";

	}

	/**
	 * 修改供应商信息
	 * 
	 * @param supplierInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("u_supplierInfo")
	@ResponseBody
	public String u_supplierInfo(SupplierVo vo, String aslist) throws Exception {

		String reuslt = SZSCMConstant.SUCCESS;

		if (null != vo) {
			try {
				reuslt = this.supplierInfoService.updateSupplierInfo(vo, aslist);
				if (reuslt == SZSCMConstant.FAIL) {
					reuslt = "WMS系统推送数据失败";
				}
			} catch (Exception e) {
				log.error("u_supplierInfo" + e.getMessage(), e);
				reuslt = SZSCMConstant.FAIL;
			}
		}
		return reuslt;
	}

	/**
	 * 跳转到供应商详情页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toDetailSupplier")
	public String toDetailSupplier(String code, ModelMap map) throws Exception {
		SupplierInfo info = supplierInfoService.getSupplierInfoCode(code);
		map.put("SupplierInfo", info);
		map.put("code", code);
		List<SupplierAccounts> purList = supplierAccountsService.getSupplierAccountsListByCode(info.getCode(), 1); // 1:购销
		List<SupplierAccounts> conList = supplierAccountsService.getSupplierAccountsListByCode(info.getCode(), 2); // 2:代销
		if (null != purList && purList.size() > 0) {
			for (SupplierAccounts sa : purList) {
				sa.setSupplierInfo(null);
			}
		}
		if (null != conList && conList.size() > 0) {
			for (SupplierAccounts sa : conList) {
				sa.setSupplierInfo(null);
			}
		}
		String purJsonStr = JsonHelper.toJson(purList);
		String conJsonStr = JsonHelper.toJson(conList);
		map.put("SupplierInfo", info);
		map.put("purJsonStr", purJsonStr);
		map.put("conJsonStr", conJsonStr);
		return "/base/detail_supplier";

	}

	/**
	 * 跳代销结算设置页面
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toSellByDai")
	public String toSellByDai(String code, String accountsType, ModelMap map) throws Exception {
		SupplierInfo info = supplierInfoService.getSupplierInfoCode(code);
		map.put("SupplierInfo", info);
		map.put("code", code);
		map.put("SupplierAccounts", supplierAccountsService.getSupplierAccountsById(code, accountsType));
		return "base/set_sell_byreplace";
	}

	/**
	 * 跳代密码修改页面
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toUpdatePass")
	public String toUpdatePass(String code, ModelMap map) throws Exception {
		if (null != code && StringUtil.isExist(code)) {
			SupplierInfo info = supplierInfoService.getSupplierInfoBySuppCode(code);
			map.put("SupplierInfo", info);
		}
		return "base/set_password";
	}

	/**
	 * 跳购销结算设置页面
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toSellByGou")
	public String toSellByGou(String code, String accountsType, ModelMap map) throws Exception {
		SupplierInfo info = supplierInfoService.getSupplierInfoCode(code);
		map.put("SupplierInfo", info);
		map.put("code", code);
		map.put("SupplierAccounts", supplierAccountsService.getSupplierAccountsById(info.getCode(), accountsType));
		return "base/set_sell_bygou";
	}

	/**
	 * 结算设置
	 * 
	 * @param id
	 * @param accounts
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("setAccountsBySell")
	@ResponseBody
	public String setAccountsBySell(String code, SupplierAccounts accounts) throws Exception {
		if (null != accounts && LogicUtil.isNotNullAndEmpty(code)) {
			try {
				supplierAccountsService.updateSupplierAccounts(code, accounts);
				return SZSCMConstant.SUCCESS;
			} catch (Exception e) {
				log.info("setAccountsBySell" + e.getMessage(), e);
			}
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 去分页查询供应商
	 * 
	 * @param supplierInfo
	 * @param pageQuery
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("pageFinderSupplier")
	public String pageFinderSupplier(SupplierVo supVo, PageQuery pageQuery, ModelMap map) throws Exception {
		List<RoleVo> roleVos = this.userService.getOwnRoleVos(UserUtils.getUserVo());
		map.put("roleVos", JsonHelper2.toJson(roleVos));
		map.put("supplier", supVo);
		return "/base/supplier_list";
	}

	/**
	 * 异步分页查询供应商
	 * 
	 * @param supplierInfo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@ResponseBody
	@RequestMapping("ajaxPageFinderSupplier")
	public String ajaxPageFinderSupplier(SupplierInfo supplierInfo, PageQuery pageQuery, ModelMap map) {
		JSONObject jsonObj = new JSONObject();
		PageFinder<SupplierInfo> pageFinder = this.supplierInfoService.querySupplierInfos(supplierInfo, pageQuery);
		jsonObj.put("Rows", pageFinder.getData());
		// ss map.put("supplierInfoList", supplierInfo);
		jsonObj.put("Total", pageFinder.getRowCount());
		return jsonObj.toJSONString();
	}

	/**
	 * 跳至品牌列表
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping("toBrandList")
	public String toBrandList(BrandVo brandVo, ModelMap map) {
		map.put("brand", brandVo);
		return "base/brand_list";
	}

	/**
	 * 异步分页
	 * 
	 * @param brandVo
	 * @param pageQuery
	 * @param map
	 * @return
	 */
	@RequestMapping("BrandList")
	@ResponseBody
	public String BrandList(BrandVo brandVo, PageQuery pageQuery, ModelMap map) {
		try {
			PageFinder<BrandVo> pagedBrandList = this.brandService.getPagedBrandList(brandVo, pageQuery);
			map.put("Rows", pagedBrandList.getData());
			map.put("Total", pagedBrandList.getRowCount());

		} catch (Exception e) {
			log.error("BrandList:" + e.getMessage(), e);
		}

		return JsonHelper2.toJson(map);
	}

	/**
	 * 根据code删除供应商
	 * 
	 * @param code
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("d_supplierInfo")
	public String d_supplierInfo(String code) throws Exception {
		if (LogicUtil.isNotNullAndEmpty(code)) {
			try {
				supplierInfoService.delSupplier(code);
				return SZSCMConstant.SUCCESS;
			} catch (Exception e) {
				log.info("d_supplierInfo" + e.getMessage(), e);
			}
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 锁定与解锁 0：解锁1：锁定
	 * 
	 * @param supplierInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("updateLockByState")
	@ResponseBody
	public String updateLockByState(SupplierInfo supplierInfo) throws Exception {
		if (null != supplierInfo && LogicUtil.isNotNullAndEmpty(supplierInfo.getCode())) {
			supplierInfoService.updateState(supplierInfo);
			return SZSCMConstant.SUCCESS;
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 删除前检查是否商品有关联
	 * 
	 * @param code
	 * @return
	 */
	@RequestMapping("checkCommodityCount")
	@ResponseBody
	public String checkCommodityCount(String code) {
		ProdSupplierVo vo = new ProdSupplierVo();
		if (LogicUtil.isNotNullAndEmpty(code)) {
			vo.setSupplierNo(code);
			List<ProdSupplier> list = prodSupplierService.getProdSupplierList(vo);
			if (null != list && list.size() > 0) {
				return SZSCMConstant.FAIL;
			}
		}
		return SZSCMConstant.SUCCESS;

	}

	/**
	 * 验证用户名
	 * 
	 * @throws Exception
	 * 
	 */
	@ResponseBody
	@RequestMapping("checkAccount")
	public String checkAccount(String account) throws Exception {
		if (null != account && LogicUtil.isNotNullAndEmpty(account)) {
			List<SupplierInfo> list = supplierInfoService.getSupplierAccount(account);
			if (null != list && list.size() > 0) {
				return SZSCMConstant.FAIL;
			}
		}
		return SZSCMConstant.SUCCESS;
	}


	/**
	 * 验证供应商名称
	 * 
	 * @throws Exception
	 * 
	 */
	@ResponseBody
	@RequestMapping("checkSupName")
	public String checkSupName(String supName) throws Exception {
		if (null != supName && LogicUtil.isNotNullAndEmpty(supName)) {
			List<SupplierInfo> list = supplierInfoService.checkSupName(supName);
			if (null != list && list.size() > 0) {
				return SZSCMConstant.FAIL;
			}
		}
		return SZSCMConstant.SUCCESS;
	}
	
	/**
	 * 帐号密码修改
	 */
	@ResponseBody
	@RequestMapping("updatePassword")
	public String updatePassword(SupplierInfo supplierInfo, ModelMap map) throws Exception {
		if (null != supplierInfo) {
			supplierInfoService.updatePwd(supplierInfo);
			return SZSCMConstant.SUCCESS;
		}
		return SZSCMConstant.FAIL;
	}

	/**
	 * 
	 * @Title: validationIsExistOldPwd
	 * @Description: 验证旧密码是否输出有误
	 * @date: 2013-6-15下午03:40:50
	 */
	@RequestMapping("checkPwd")
	@ResponseBody
	public String checkPwd(String code, String oldPwd) {
		try {
			String pass = MD5Util.MD5Encode(oldPwd, "");
			SupplierInfo supplierInfo = this.supplierInfoService.getSupplierInfoCode(code);
			if (LogicUtil.isNotNull(supplierInfo)) {
				if (!supplierInfo.getPassword().equals(pass)) {
					return SZSCMConstant.SUCCESS;
				}
			}
		} catch (Exception e) {
			return SZSCMConstant.FAIL;
		}

		return SZSCMConstant.FAIL;
	}

	@RequestMapping("doExportExcel")
	public void doExportExcel(SupplierVo supVo, HttpServletResponse response) throws IOException {

		supVo.setSupName(URLDecoder.decode(supVo.getSupName(), "UTF-8"));
		String tName = DateUtil.parseDate(new Date(), "yyyyMMddHHmmss");
		response.addHeader("content-disposition", "attachment;filename=supplierInfo" + tName + ".xls");
		response.setContentType("application/vnd.ms-excel");

		List<?> list = this.supplierInfoService.getExportExcel(supVo);

		SupplierExcel se = new SupplierExcel();
		se.createSheet(list, response.getOutputStream());
	}

	public static String string2Json(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			switch (c) {
			case '\"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '/':
				sb.append("\\/");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '%':
				sb.append("\\\\t");
				break;
			default:
				sb.append(c);
			}
		}
		return sb.toString();
	}

	@RequestMapping("supplierList")
	@ResponseBody
	public String getSupplierList() {
		return JsonHelper2.toJson(supplierInfoService.getAllSupplierInfo());
	}

	public static void main(String[] args) {
		System.out.println(string2Json("a%"));
	}


}
